package me.kafeitu.demo.activiti.web;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.DriverManager;
import java.util.Properties;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import me.kafeitu.demo.activiti.util.UserUtil;

import org.apache.ibatis.jdbc.ScriptRunner;
import org.flowable.idm.api.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.tanghom.app.system.service.UserService;

import com.mysql.jdbc.Connection;

/**
 * 演示首页控制器,主要为工作流
 *
 * @author tanghom
 */
@Controller
@RequestMapping("/demo")
public class DemoController {
    @Resource
    private UserService userService;

    /**
     * add@byron
     * 演示demo页面
     */    
    @RequestMapping(value = "/index")
    public String index(HttpSession session) {
    	User activitiUser = UserUtil.getUserFromSession(session);
    	if(activitiUser==null)
    		return "redirect:/user/login";
        return "/demo/index";
    }

    @RequestMapping(value = "/welcome")
    public String welcome(HttpSession session) {
    	User activitiUser = UserUtil.getUserFromSession(session);
    	if(activitiUser==null)
    		return "redirect:/user/login";
        return "/demo/welcome";
    }  
    
    /**
     * 安装demo数据
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/install", method = RequestMethod.GET)
    @ResponseBody
    public String install() throws Exception {

        try {
            Properties props = org.apache.ibatis.io.Resources.getResourceAsProperties("jdbc.properties");
            String driver = props.getProperty("jdbc.driverClassName");
            String url = props.getProperty("jdbc.url");
            String username = props.getProperty("jdbc.username");
            String password = props.getProperty("jdbc.password");
            Class.forName(driver).newInstance();
            Connection conn = (Connection) DriverManager.getConnection(url, username, password);
            ScriptRunner runner = new ScriptRunner(conn);
            runner.setErrorLogWriter(null);
            runner.setLogWriter(null);
            InputStream in = getClass().getResourceAsStream("/sql/db_demo_install.sql");
            if(in!=null){
            	runner.runScript((new InputStreamReader(in,"UTF-8")));
            }
            else{
            	return "读取sql/db_demo_install.sql文件失败！";
            }

        } catch (Exception e) {
            e.printStackTrace();
            return "初始化失败！请联系管理员" + e;
        }

        return "初始化成功";
    }

}
